import React from 'react';
import {Modal, Form, Input, DatePicker, Select, Switch, Alert, Row, Col} from 'antd';
import moment from 'moment';
import form, {emptyRule} from '../_/form';
import redux from '../_/redux';
import {context} from '../_';
import py from '../_/pinyin';
import {app} from '../app';
import _name, {defaultPassword} from './dev';
import EditorDepartment from './editorDepartment';
const FormItem = Form.Item;
const dataName = 'dataEdit';

@context('params')
@form({
    data: dataName,
    newData: {
        Status: true,
        DisplayOrder: 0,
        DateStart: moment(),
        DataEnd: null
    }
})
@redux(_name, {
    data: ({[dataName]: data}) => (data ? data.Id : '-'),
    actions: ['create', 'modify']
})
@redux('app', {
    data: 'cfg.width',
    prefix: 'app'
})
export default class EditorModel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            startValue: null,
            endValue: null
        };
    }

    state = {authData: {}};

    componentWillReceiveProps(props) {
        const {[dataName]: data} = props;
        const {[dataName]: rawdata} = this.props;
        if (data !== rawdata) {
            this.reset(data);
        }
    }

    onState = (flag, ...args) => {
        switch (flag) {
            //模块操作命令发生改变
        case 'authchange': {
            this.setState({authData: args[0]});
            break;
        }
        }
    };
    //开始
    onStartChange = (value) => {
        this.setState({
            startValue: value
        });
    };
    //结束
    onEndChange = (value) => {
        this.setState({
            endValue: value
        });
    };
    disabledStartDate = (startValue) => {
        if (!startValue || !this.state.endValue) {
            return false;
        }
        return startValue >= this.state.endValue;
    };
    disabledEndDate = (endValue) => {
        if (!endValue || !this.state.startValue) {
            return false;
        }
        return endValue <= this.state.startValue;
    };

    reset = (data, opened = true) => {
        const authData = JSON.parse(data.AuthData || '{}');
        let start = null;
        if (data && data.DataStart) {
            start = data.DataStart;
        } else if (this.props.isNew && opened) {
            start = moment();
        }
        const end = data ? data.DataEnd || null : null;
        this.setState({authData, errMsg: false, startValue: start, endValue: end});
        if (!opened) {
            this.setState({startValue: null, endValue: null});
            this.props.form.resetFields();
        }
    };

    render() {
        const {[dataName]: data, form, onState} = this.props;
        const {authData} = this.state;
        const {getFieldDecorator: fp} = form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
        };
        const onOk = () => {
            form.validateFieldsAndScroll((err, vals) => {
                if (err) {
                    this.setState({errMsg: true});
                } else {
                    this.setState({errMsg: false});
                    vals.AuthData = JSON.stringify(this.state.authData);
                    onState("save", vals);
                    vals.DateStart = vals.DateStart ? vals.DateStart.format('YYYY-MM-DD') : null;
                    vals.DateEnd = vals.DateEnd ? vals.DateEnd.format('YYYY-MM-DD') : null;
                    if (this.props.isNew) {
                        this.props.create(vals, this.props);
                    } else {
                        if (vals.Password === defaultPassword) {
                            delete vals.Password;
                            delete vals.Password2;
                        }
                        this.props.modify(vals, this.props);
                    }
                }
            });
        };
        const onCancel = () => {
            form.setFieldsValue(data);
            onState("cancel");
            this.reset(data, false);
        };

        const nameInputOption = {
            rules: [
                emptyRule('请输入姓名'),
                {min: 1, max: 50}
            ],
            onChange: (e) => {
                if (this.props.isNew) {
                    const value = e.target.value;
                    form.setFieldsValue({NameJp: value ? py(value) : value});
                }
            }
        };
        //密码
        const passwordInputOption = {
            rules: [
                {required: true, message: '请输入密码'},
                {min: 1, max: 50, whitespace: true}
            ],
            onChange: () => {
                form.setFieldsValue({Password2: null});
            }
        };
        //确认密码
        const password2InputOption = {
            rules: [
                {required: true, message: '请输入确认密码'},
                {min: 1, max: 50, whitespace: true},
                {
                    validator: (rule, value, callback) => {
                        const form = this.props.form;
                        const password = form.getFieldValue('Password');
                        if (value && value !== password) {
                            callback('两次输入密码不一致！');
                        } else {
                            callback();
                        }
                    }
                }
            ]
        };
        //时效日期
        const DateStart = {
            rules: [
                {required: false, type: 'object', message: '请设置查询开始时间'}
            ],
            format: "yyyy-MM-dd",
            value: this.state.startValue,
            onChange: this.onStartChange
        };
        const DateEnd = {
            rules: [
                {required: false, type: 'object', message: '请设置查询结束时间'}
            ],
            format: "yyyy-MM-dd",
            value: this.state.endValue,
            onChange: this.onEndChange
        };

        const alert = this.state.errMsg ?
            (<Alert message="输入项有错误,请检查后再试!" type="error" showIcon/>)
            : "";

        const width = Math.min(app.maxWidthModal, this.props.appdata - 10);
        const colOpts = {
            xs: {span: 24},
            sm: {span: 12}
        };
        return (
            <Modal
                width={width}
                okText="保存"
                maskClosable={false}
                onOk={onOk}
                onCancel={onCancel}
                wrapClassName={`${_name}Modal`}
                {...this.props}
            >
                {alert}
                <Form>
                    {fp("Id")(<Input type="hidden"/>)}
                    <Row>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label={`编码`}>
                                {fp("Code", {rules: [emptyRule('请输入编码'), {min: 1, max: 50}]})(<Input />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label={`账户`}>
                                {fp("UserName", {rules: [emptyRule('请输入账户'), {min: 1, max: 50}]})(<Input />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label={`姓名`}>
                                {fp("Name", nameInputOption)(<Input />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="检索码">
                                {fp("NameJp", {rules: [{min: 1, max: 255}]})(<Input/>)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="密码">
                                {fp("Password", passwordInputOption)(<Input type="password"/>)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="密码确认">
                                {fp("Password2", password2InputOption)(<Input type="password"/>)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="职称">
                                {fp("TitleCode")(<Select />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="时效开始">
                                {fp("DateStart", DateStart)(<DatePicker
                                    disabledDate={this.disabledStartDate}
                                />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="时效结束">
                                {fp("DateEnd", DateEnd)(<DatePicker
                                    disabledDate={this.disabledEndDate}
                                />)}
                            </FormItem>
                        </Col>
                        <Col {...colOpts}>
                            <FormItem {...formItemLayout} label="状态">
                                {fp("Status", {valuePropName: 'checked'})(
                                    <Switch checkedChildren={'启动'} unCheckedChildren={'停用'}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col xs={{span: 20, push: 2, pull: 2}}>
                            <EditorDepartment
                                width={width}
                                onState={this.onState}
                                defVal={authData}
                            />
                        </Col>
                    </Row>
                </Form>
            </Modal>
        );
    }
}
